package com.jmx.yp.struts.employee;

import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.security.providers.encoding.Md5PasswordEncoder;

import com.jmx.yp.common.SysConstants;
import com.jmx.yp.entity.GroupEmployee;
import com.jmx.yp.entity.Role;
import com.jmx.yp.exception.ErrorCode;
import com.jmx.yp.exception.HandlerException;
import com.jmx.yp.service.employee.IEmployeeService;
import com.jmx.yp.service.group.IGroupinfoService;
import com.jmx.yp.service.role.IRoleService;
import com.opensymphony.xwork2.ActionContext;

/**
 * 
 * 功能描述：
 *			处理员工管理的业务控制
 * @author Jenny
 *
 * Date:2011-1-18 下午11:40:43
 */
public class EmployeeAction {
	
	private static Logger log = (Logger)Logger.getLogger(EmployeeAction.class);

	private IEmployeeService employeeService;
	
	private IGroupinfoService groupService;
	
	private IRoleService roleService;
	
	private Md5PasswordEncoder md5;
	
	/**员工类型-超级管理员*/
	private final int EMPLOYEE_TYPE_SUPERADMIN = 0;
	
	/**员工类型-杰马逊员工*/
	private final int EMPLOYEE_TYPE_JMX = 1;
	
	/**员工类型-代理组织机构员工*/
	private final int EMPLOYEE_TYPE_GROUP = 2;
	
	
	public void setEmployeeService(IEmployeeService employeeService){
		this.employeeService = employeeService;
	}
	
	public void setMd5(Md5PasswordEncoder md5){
		this.md5 = md5;
	}
	
	public void setGroupService(IGroupinfoService groupService){
		this.groupService = groupService;
	}
	
	public void setRoleService(IRoleService roleService){
		this.roleService = roleService;
	}
	
	/**
	 * 查询员工列表入口
	 * 		完成初始化工作，如果是超级管理员，默认查询JMX
	 * 
	 * @return
	 */
	public String queryEmployeeList(){
		GroupEmployee employee = (GroupEmployee)ActionContext.getContext().getSession().get("user");
		
		try{
			if(employee.getGroup_srl() == null){
				Map map = groupService.getGroupNameById(employee.getGroup_srl());
				if(map != null){
					groupId = (Long)map.get("SERIALID");
					groupName = (String)map.get("GROUP_NAME");					
					groupCode = (String)map.get("GROUP_CODE");
				}
			}else{
				boolean jmxFlag = groupService.isBlongToJMX(employee.getGroup_srl());
				if(jmxFlag){					
					employeeType = EMPLOYEE_TYPE_JMX;
				}else{					
					employeeType = EMPLOYEE_TYPE_GROUP;
				}
				
				originalGroupId = employee.getGroup_srl();
				originalGroupName = employee.getGroup_name();
				groupName = employee.getGroup_name();
				groupCode = employee.getGroup_code();
			}
			
		}catch(Exception e){
			e.printStackTrace();
			log.error("EmployeeAction queryEmployeeList error: " + e.getMessage());
		}
		
		return "query";
	}
	
	/**
	 * 根据条件查询员工
	 * 		1、超级管理员，默认只查询JMX的员工
	 * 		2、杰马逊管理员，则查询所有的
	 * 		3、组织管理员查询，如果组织代码或组织名称为空，则默认查询本级组织的员工，否则加入对输入的组织
	 * 		       的判断，是否是属于该组织所属的子树，否则不允许查询
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String queryEmployee(){
		try{
			Map map = employeeService.queryEmployeeList(queryGroupCode, queryGroupName, 
					queryEmployeeCode, queryEmployeeName, nowPage);
			
			result = JSONObject.fromObject(map);
	
		}catch(Exception e){
			e.printStackTrace();
			log.error("EmployeeAction queryEmployee error: " + e.getMessage());
			results = ErrorCode.COMMON_ERROR;
		}
		return "success";
	}
	
	
	
	/**
	 * 初始化新增员工入口
	 * 		准备工作：
	 *              1、判断操作者的组织机构，根据操作者所属的组织机构显示其所属的及下一级组织机构（直接通过界面选择）
	 *              2、可以分配的角色，如果组织机构是杰马逊，角色分为两类（内部员工角色、机构默认角色--该类角色对组织机构员工透明）
	 * @return
	 */
	public String initAddEmployee(){
		GroupEmployee employee = (GroupEmployee)ActionContext.getContext().getSession().get("user");
		String forward = "error";
		try{
			//如果是默认超级管理员，即员工的组织编号为空时，就不判断组织，直接显示杰马逊内部角色即可
			if(employee.getGroup_srl() == null){				
				roleList = roleService.getEmployeeRole(Role.ROLE_TYPE_JMX, null, false);

				//设置组织机构,若ID为空，直接设置为杰马逊
				Map map = groupService.getGroupNameById(employee.getGroup_srl());
				if(map != null){
					groupId = (Long)map.get("SERIALID");
					groupName = (String)map.get("GROUP_NAME");					
					groupCode = (String)map.get("GROUP_CODE");
				}
				employeeType = EMPLOYEE_TYPE_SUPERADMIN;
			}else{
				boolean jmxFlag = groupService.isBlongToJMX(employee.getGroup_srl());
				if(jmxFlag){
					roleList = roleService.getEmployeeRole(null, null, true);
					employeeType = EMPLOYEE_TYPE_JMX;
				}else{
					roleList = roleService.getEmployeeRole(Role.ROLE_TYPE_GROUP, employee.getGroup_srl(), false);
					employeeType = EMPLOYEE_TYPE_GROUP;
				}
				
				originalGroupId = employee.getGroup_srl();
				originalGroupName = employee.getGroup_name();
				groupCode = employee.getGroup_code();
			}
			
			//界面初始化数据
			educationMap = SysConstants.getEducationMap();
			
			forward = "addEmployee";
		}catch(Exception e){
			log.error("EmployeeAction initAddEmployee error: " + e.getMessage());
			e.printStackTrace();
		}
		return forward;
	}
	
	/**
	 *  新增机构员工
	 * @return
	 */
	public String addEmployee(){
		GroupEmployee employee = (GroupEmployee)ActionContext.getContext().getSession().get("user");
		
		try{
			employeeService.addEmployee(assembleGroupEmployee(employee.getGrpemp_id()));
			
			results = "success";
		}catch(HandlerException ae){
			results = ae.toString();
		}catch(Exception e){
			log.error("EmployeeAction addEmployee error: " + e.getMessage());
			e.printStackTrace();
			results = ErrorCode.COMMON_ERROR;
		}

		return "success";
	}
	
	/**
	 * 装配GroupEmployee对象
	 * @return
	 */
	private GroupEmployee assembleGroupEmployee(String operator){
		GroupEmployee employee = new GroupEmployee();
		employee.setGroup_srl(groupId);
		employee.setGrpemp_addr(address);
		employee.setGrpemp_birthday(birthday);
		employee.setGrpemp_email(email);
		employee.setGrpemp_gender(sex);
		employee.setGrpemp_id(loginName);
		employee.setGrpemp_name(nameFirst + nameLast);
		employee.setGrpemp_name_first(nameFirst);
		employee.setGrpemp_name_last(nameLast);
		employee.setGrpemp_postalcode(postalcode);
		if(pass != null && pass.trim().length() > 0)
			employee.setGrpemp_pwd(md5.encodePassword(pass.trim(), loginName.trim())); 
		else
			employee.setGrpemp_pwd(null);
		employee.setGrpemp_tel(tel);
		employee.setGrpemp_tel_area(telArea);
		employee.setGrpemp_tel_cn(telCn);
		if(Integer.parseInt(education) != 0)
			employee.setGrpemp_topedu(education);
		employee.setGtalk(gtalk);
		employee.setInvalid(GroupEmployee.VALID);
		employee.setMsn(msn);
		employee.setOicq(qicq);
		employee.setOperatetime(new Date());
		employee.setRemark(remark);
		employee.setRole_srl(roleId);
		employee.setSkpye(skpye);
		employee.setState(SysConstants.STATE_NORMAL);
		employee.setYahoomsg(yahoomsg);
		employee.setOperator(operator);
		
		return employee;
	}
	
	/**
	 * 查找员工组织入口
	 * @return
	 */
	public String initSearchGroup(){
		return "searchGroup";
	}
	
	public String getGroupRoot(){
		GroupEmployee employee = (GroupEmployee)ActionContext.getContext().getSession().get("user");
		
		try{
			if(employeeType == EMPLOYEE_TYPE_JMX)
				treeNode = groupService.getGroupRoot(employee.getGroup_srl(), employee.getGroup_name(), 
						employee.getGroup_code(), queryGroupName, queryGroupCode, true);
			else
				treeNode = groupService.getGroupRoot(originalGroupId, originalGroupName,
						groupCode, queryGroupName, queryGroupCode, false);
			 
			results = "success";
			
		}catch(HandlerException he){
			results = he.toString();
		}catch(Exception e){
			e.printStackTrace();
			log.error("EmployeeAction getGroupRoot error: " + e.getMessage());
			results = ErrorCode.COMMON_ERROR;
		}
		
		return "success";
	}
	
	/**
	 * 查找员工组织
	 * @return
	 */
	public String searchGroup(){
		GroupEmployee employee = (GroupEmployee)ActionContext.getContext().getSession().get("user");
		String xmlDoc = "";
		
		try{			
			if(employeeType == EMPLOYEE_TYPE_JMX)
				xmlDoc = groupService.getGroupTreeXML(rootGroupId, rootGroupName, groupCode, employee.getGroup_srl());
			else
				xmlDoc = groupService.getGroupTreeXML(rootGroupId, rootGroupName, groupCode,null);
		
		//System.out.println(xmlDoc);
		
			HttpServletResponse response = ServletActionContext.getResponse();
	        response.setContentType("text/xml;charset=UTF-8");   
	        response.setHeader("Cache-Control","no-cache");
	        PrintWriter out = response.getWriter();  
	        
	        out.write(xmlDoc); 
	        out.flush();			
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 修改员工：入口
	 *     准备工作：根据ID查询对应的员工对象
	 *     备注：其中帐号、所属组织机构不允许再进行修改
	 * @return
	 */
	public String initUpdateEmployee(){
		String forward = "error";
		
		try{
			GroupEmployee employee = employeeService.getEmployeeById(Long.parseLong(serialid));
			
			setEmployeePropertiesValue(employee);
			
			//界面初始化数据
			educationMap = SysConstants.getEducationMap();
			
			//如果是默认超级管理员，即员工的组织编号为空时，就不判断组织，直接显示杰马逊内部角色即可
			if(employee.getGroup_srl() == null){				
				roleList = roleService.getEmployeeRole(Role.ROLE_TYPE_JMX, null, false);

				employeeType = EMPLOYEE_TYPE_SUPERADMIN;
			}else{
				boolean jmxFlag = groupService.isBlongToJMX(employee.getGroup_srl());
				if(jmxFlag){
					roleList = roleService.getEmployeeRole(null, null, true);
					employeeType = EMPLOYEE_TYPE_JMX;
				}else{
					roleList = roleService.getEmployeeRole(Role.ROLE_TYPE_GROUP, employee.getGroup_srl(), false);
					employeeType = EMPLOYEE_TYPE_GROUP;
				}
			}
			
			forward = "updateEmployee";
		}catch(Exception e){
			e.printStackTrace();
			log.error("EmployeeAction initUpdateEmployee error: " + e.getMessage());
		}
		return forward;
	}
	
	/**
	 * 设置界面的属性值
	 * @param employee
	 */
	private void setEmployeePropertiesValue(GroupEmployee employee){
		loginName = employee.getGrpemp_id();
		roleId = employee.getRole_srl();
		nameFirst = employee.getGrpemp_name_first();
		nameLast = employee.getGrpemp_name_last();
		groupName = employee.getGroup_name();
		groupId = employee.getGroup_srl();
		sex = employee.getGrpemp_gender();
		birthday = employee.getGrpemp_birthday();
		if(employee.getGrpemp_topedu() != null &&
		   employee.getGrpemp_topedu().length() > 0)
			education = employee.getGrpemp_topedu();
		else
			education = "0";
		postalcode = employee.getGrpemp_postalcode();
		address = employee.getGrpemp_addr();
		email = employee.getGrpemp_email();
		telCn = employee.getGrpemp_tel_cn();
		telArea = employee.getGrpemp_tel_area();
		tel = employee.getGrpemp_tel();
		qicq = employee.getOicq();
		msn = employee.getMsn();
		yahoomsg = employee.getYahoomsg();
		skpye = employee.getSkpye();
		gtalk = employee.getGtalk();
		remark = employee.getRemark();
		serialid = employee.getSerialid().toString();
	}
	
	/**
	 * 更新员工信息
	 * @return
	 */
	public String updateEmployee(){
		GroupEmployee user = (GroupEmployee)ActionContext.getContext().getSession().get("user");
		try{
			
			GroupEmployee employee = assembleGroupEmployee(user.getGrpemp_id());
			employee.setSerialid(Long.parseLong(serialid));
			employeeService.updateEmployee(employee);
			
			results = "success";
		}catch(Exception e){
			e.printStackTrace();
			log.error("EmployeeAction updateEmployee error: " + e.getMessage());
			results = ErrorCode.COMMON_ERROR;
		}
		
		return "success";
	}
	
	/**
	 * 删除员工 支持批量删除
	 * 		员工ID用;相隔
	 * @return
	 */
	public String deleteEmployee(){
		GroupEmployee user = (GroupEmployee)ActionContext.getContext().getSession().get("user");
		
		try{
			employeeService.deleteEmployee(serialid, user.getGrpemp_id());
			results = "success";
		}catch(Exception e){
			e.printStackTrace();
			log.error("EmployeeAction deleteEmployee error: " + e.getMessage());
			results = ErrorCode.COMMON_ERROR;
		}
		
		return "success";
	}
	
	public String detailEmployee(){
		String forward = "error";
		
		try{
			GroupEmployee employee = employeeService.getEmployeeById(Long.parseLong(serialid));
			
			setEmployeePropertiesValue(employee);
			
			//界面初始化数据
			educationMap = SysConstants.getEducationMap();
			
			//如果是默认超级管理员，即员工的组织编号为空时，就不判断组织，直接显示杰马逊内部角色即可
			if(employee.getGroup_srl() == null){				
				roleList = roleService.getEmployeeRole(Role.ROLE_TYPE_JMX, null, false);

				employeeType = EMPLOYEE_TYPE_SUPERADMIN;
			}else{
				boolean jmxFlag = groupService.isBlongToJMX(employee.getGroup_srl());
				if(jmxFlag){
					roleList = roleService.getEmployeeRole(null, null, true);
					employeeType = EMPLOYEE_TYPE_JMX;
				}else{
					roleList = roleService.getEmployeeRole(Role.ROLE_TYPE_GROUP, employee.getGroup_srl(), false);
					employeeType = EMPLOYEE_TYPE_GROUP;
				}
			}
			
			forward = "detailEmployee";
		}catch(Exception e){
			e.printStackTrace();
			log.error("EmployeeAction detailEmployee error: " + e.getMessage());
		}
		return forward;
	}
	
	/**角色列表**/
	private List roleList;
	
	/*结果**/
	private String results;
	
	/*初始化列表信息*/
	private Map<Integer, String> educationMap;
	
	//用于标识员工类型
	private Integer employeeType;
	
	
	/*新增属性**/
	private String loginName; //登录帐号（即员工编号,员工编号需要由组织机构编号+自定义编号）
	private String pass; //密码
	private Long roleId; //角色ID
	private String nameFirst;
	private String nameLast;
	private String groupName;
	private Long groupId;
	private String originalGroupName;  //用来保存操作员组织机构名称
	private Long originalGroupId;    //用来保存操作员组织机构ID
	private String groupCode; //机构编码，用于生成登录帐号
	private String sex;
	private String birthday;
	private String education;
	private String postalcode;
	private String address;
	private String email;
	private String telCn;
	private String telArea;
	private String tel;
	private String qicq;
	private String msn;
	private String yahoomsg;
	private String skpye;
	private String gtalk;
	private String remark;
	private String serialid;
	
	//组织机构查询界面查询参数
	private String queryGroupCode;
	private String queryGroupName;
	
	//组织机构记录根ID及根Name,以便于删除
	private Long rootGroupId;
	private String rootGroupName;
	
	//记录树ID供页面清除节点
	private String treeNode;
	
	//员工列表查询界面查询参数
	private String queryEmployeeCode;
	private String queryEmployeeName;
	
	private int nowPage;
	
	private JSONObject result;
	
	
	
	public String getSerialid() {
		return serialid;
	}

	public void setSerialid(String serialid) {
		this.serialid = serialid;
	}

	public JSONObject getResult() {
		return result;
	}

	public void setResult(JSONObject result) {
		this.result = result;
	}

	public void setNowPage(int nowPage){
		this.nowPage = nowPage;
	}
	
	public int getNowPage(){
		return nowPage;
	}
	
	public String getQueryEmployeeCode() {
		return queryEmployeeCode;
	}

	public void setQueryEmployeeCode(String queryEmployeeCode) {
		this.queryEmployeeCode = queryEmployeeCode;
	}

	public String getQueryEmployeeName() {
		return queryEmployeeName;
	}

	public void setQueryEmployeeName(String queryEmployeeName) {
		this.queryEmployeeName = queryEmployeeName;
	}

	public Long getRootGroupId() {
		return rootGroupId;
	}

	public void setRootGroupId(Long rootGroupId) {
		this.rootGroupId = rootGroupId;
	}

	public String getRootGroupName() {
		return rootGroupName;
	}

	public void setRootGroupName(String rootGroupName) {
		this.rootGroupName = rootGroupName;
	}

	public void setTreeNode(String treeNode){
		this.treeNode = treeNode;
	}

	public String getTreeNode(){
		return treeNode;
	}
	
	public String getQueryGroupCode() {
		return queryGroupCode;
	}

	public void setQueryGroupCode(String queryGroupCode) {
		this.queryGroupCode = queryGroupCode;
	}

	public String getQueryGroupName() {
		return queryGroupName;
	}

	public void setQueryGroupName(String queryGroupName) {
		this.queryGroupName = queryGroupName;
	}

	public Integer getEmployeeType() {
		return employeeType;
	}

	public void setEmployeeType(Integer employeeType) {
		this.employeeType = employeeType;
	}

	public String getNameFirst() {
		return nameFirst;
	}

	public void setNameFirst(String nameFirst) {
		this.nameFirst = nameFirst;
	}

	public String getNameLast() {
		return nameLast;
	}

	public void setNameLast(String nameLast) {
		this.nameLast = nameLast;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getBirthday() {
		return birthday;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}

	public String getEducation() {
		return education;
	}

	public void setEducation(String education) {
		this.education = education;
	}

	public String getPostalcode() {
		return postalcode;
	}

	public void setPostalcode(String postalcode) {
		this.postalcode = postalcode;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getTelCn() {
		return telCn;
	}

	public void setTelCn(String telCn) {
		this.telCn = telCn;
	}

	public String getTelArea() {
		return telArea;
	}

	public void setTelArea(String telArea) {
		this.telArea = telArea;
	}

	public String getTel() {
		return tel;
	}

	public void setTel(String tel) {
		this.tel = tel;
	}

	public String getQicq() {
		return qicq;
	}

	public void setQicq(String qicq) {
		this.qicq = qicq;
	}

	public String getMsn() {
		return msn;
	}

	public void setMsn(String msn) {
		this.msn = msn;
	}

	public String getYahoomsg() {
		return yahoomsg;
	}

	public void setYahoomsg(String yahoomsg) {
		this.yahoomsg = yahoomsg;
	}

	public String getSkpye() {
		return skpye;
	}

	public void setSkpye(String skpye) {
		this.skpye = skpye;
	}

	public String getGtalk() {
		return gtalk;
	}

	public void setGtalk(String gtalk) {
		this.gtalk = gtalk;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	public String getGroupCode() {
		return groupCode;
	}

	public void setGroupCode(String groupCode) {
		this.groupCode = groupCode;
	}

	public Map<Integer, String> getEducationMap() {
		return educationMap;
	}

	public void setEducationMap(Map<Integer, String> educationMap) {
		this.educationMap = educationMap;
	}

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}
	
	public String getResults() {
		return results;
	}

	public void setResults(String results) {
	
		this.results = results;
	}
	public void setRoleList(List list){
		this.roleList = list;
	}
	
	public List getRoleList(){
		return roleList;
	}

	public String getGroupName() {
		return groupName;
	}

	public void setGroupName(String groupName) {
		this.groupName = groupName;
	}

	public Long getGroupId() {
		return groupId;
	}

	public void setGroupId(Long groupId) {
		this.groupId = groupId;
	}

	public Md5PasswordEncoder getMd5() {
		return md5;
	}

	public Long getRoleId() {
		return roleId;
	}

	public void setRoleId(Long roleId) {
		this.roleId = roleId;
	}

	public String getOriginalGroupName() {
		return originalGroupName;
	}

	public void setOriginalGroupName(String originalGroupName) {
		this.originalGroupName = originalGroupName;
	}

	public Long getOriginalGroupId() {
		return originalGroupId;
	}

	public void setOriginalGroupId(Long originalGroupId) {
		this.originalGroupId = originalGroupId;
	}

}
